package com.zysdev.avtask2

import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.util.Log
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class AudioCodec : Thread() {

    //最小缓冲区，值要大于最小要求
    private var minBufferSize: Int = 0

    private var audioRecord: AudioRecord? = null

    private var state: RecordState = RecordState.IDLE

    private var tempFile: File? = null

    private var recordManager: RecordManager? = null

    private enum class RecordState {
        IDLE,
        RECORDING,
        PAUSE,
        STOP,
    }

    fun startAudio(recordManager: RecordManager) {
        this.recordManager = recordManager
        minBufferSize = AudioRecord.getMinBufferSize(
            44100,
            AudioFormat.CHANNEL_IN_DEFAULT,
            AudioFormat.ENCODING_PCM_16BIT
        )

        checkAudioRecordNuLL()
        val tempPath = getTempPCMFilePath()
        Log.e("---", "pcm_tempPath=$tempPath")
        tempFile = File(tempPath)

        start()
    }

    private fun checkAudioRecordNuLL() {
        audioRecord = AudioRecord(
            MediaRecorder.AudioSource.MIC,
            44100,
            AudioFormat.CHANNEL_IN_DEFAULT,
            AudioFormat.ENCODING_PCM_16BIT,
            minBufferSize
        )
    }

//    fun resumeAudio() {
//        checkAudioRecordNuLL()
//
//    }

    fun stopAudio() {
        if (state == RecordState.IDLE) {
            return
        }
        state = RecordState.STOP

    }

    override fun run() {

        var fos: FileOutputStream? = null

        try {
            state = RecordState.RECORDING
            fos = FileOutputStream(tempFile)
            audioRecord?.startRecording();
            val bufferArray = ByteArray(minBufferSize)
            while (state == RecordState.RECORDING) {
                val end: Int = audioRecord?.read(bufferArray, 0, bufferArray.size)!!
                fos.write(bufferArray, 0, end)
                fos.flush()
            }
            audioRecord?.stop()
            audioRecord?.release()
            audioRecord = null
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            fos?.close()
        }
        if (tempFile != null) {
            Log.e("---", "tempFile.len=${tempFile!!.length()}")
            Utils.convertPcm2Wav(
                tempFile!!.absolutePath,
                getTempWAVFilePath(),
                44100,
                1,
                16,
            )
        }
    }

    fun getTempPCMFilePath(): String {
        return recordManager?.getTempPath()!! + "/${System.currentTimeMillis()}.pcm"
    }

    fun getTempWAVFilePath(): String {
        return recordManager?.getTempPath()!! + "/${System.currentTimeMillis()}.wav"
    }


}